package com.example.peibei.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dingtao.common.bean.Order;
import com.dingtao.common.bean.OrderComment;
import com.dingtao.common.bean.OrderDetail;
import com.dingtao.common.bean.RefreshResult;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.GlideUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.CateOrderPresenter;
import com.example.peibei.service.presenter.CollectPresenter;
import com.example.peibei.service.presenter.OrderCommentPresenter;
import com.example.peibei.service.presenter.OrderDetailPresenter;
import com.example.peibei.ui.adapter.OrderCommentAdapter;
import com.example.peibei.ui.adapter.OrderLikeListAdapter;
import com.example.peibei.ui.weight.CenterDialog;
import com.linxiao.framework.dialog.BottomDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class OrderDetailActivity extends WDActivity {
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.tv_week)
    TextView tv_week;
    @BindView(R.id.tv_other)
    TextView tv_other;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_category)
    TextView tv_category;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.iv_img_one)
    ImageView iv_img_one;
    @BindView(R.id.iv_img_two)
    ImageView iv_img_two;
    @BindView(R.id.iv_img_three)
    ImageView iv_img_three;
    @BindView(R.id.ll_imgs)
    LinearLayout ll_imgs;
    @BindView(R.id.bt_submit)
    Button bt_submit;
    @BindView(R.id.ll_collect)
    LinearLayout ll_collect;
    @BindView(R.id.ll_collected)
    LinearLayout ll_collected;
    @BindView(R.id.rl_pl)
    RelativeLayout rl_pl;
    @BindView(R.id.tv_pj_num)
    TextView tv_pj_num;
    @BindView(R.id.tv_hp)
    TextView tv_hp;
    @BindView(R.id.rv_comment)
    RecyclerView rv_comment;
    @BindView(R.id.rv_like)
    RecyclerView rv_like;
    @BindView(R.id.tv_like)
    TextView tv_like;
    @BindView(R.id.tv_liulan)
    TextView tv_liulan;
    @BindView(R.id.tv_unit)
    TextView tv_unit;


    private String publishOrderId;
    private SPUtils spUtils;
    private String token;
    private CollectPresenter collectPresenter;
    private boolean isShow;
    private String unit;
    private long userId;
    private String mid;
    private OrderCommentPresenter orderCommentPresenter;
    private OrderCommentAdapter orderCommentAdapter;
    private List<OrderComment.ListDTO> commentList = new ArrayList<>();
    List<Order.RecordsDTO> orders;
    private OrderLikeListAdapter orderLikeListAdapter;
    private CateOrderPresenter homeOrderPresenter;
    private String cityName = "";
    private String cityCode = "";
    private int age = 0;
    private String auto = "";
    private String gender = "";
    private String price = "";
    private String categoryId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        publishOrderId = bundle.getString("publishOrderId");
        String type = bundle.getString("type");
        iv_back.setOnClickListener(v -> finish());
        orders = new ArrayList<>();
        spUtils = new SPUtils(OrderDetailActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        userId = spUtils.getLong(SpConstant.USER_MID);
        OrderDetailPresenter orderDetailPresenter = new OrderDetailPresenter(new OrderDetailCall());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rv_comment.setLayoutManager(linearLayoutManager);
        orderCommentAdapter = new OrderCommentAdapter(commentList);
        rv_comment.setAdapter(orderCommentAdapter);
        orderCommentPresenter = new OrderCommentPresenter(new OrderCommentCall());
        if (TextUtils.isEmpty(token)) {
            orderDetailPresenter.reqeust(publishOrderId, "");
        } else {
            orderDetailPresenter.reqeust(publishOrderId, "Bearer " + token);
        }
        collectPresenter = new CollectPresenter(new CollectCall());
        if (TextUtils.isEmpty(type)) {
            bt_submit.setVisibility(View.VISIBLE);
        } else {
            bt_submit.setVisibility(View.GONE);
        }
        rv_like.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        orderLikeListAdapter = new OrderLikeListAdapter(orders);
        rv_like.setAdapter(orderLikeListAdapter);
        homeOrderPresenter = new CateOrderPresenter(new OrderCall());
        orderLikeListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Order.RecordsDTO order = (Order.RecordsDTO) adapter.getData().get(position);
            String publishOrderId = order.getPublishOrderId();
            Bundle bundle1 = new Bundle();
            bundle1.putString("publishOrderId", publishOrderId);
            intent(OrderDetailActivity.class, bundle1);
        });
    }

    @OnClick(R.id.bt_submit)
    public void submitOrder() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (TextUtils.isEmpty(unit)) return;

        Bundle bundle = new Bundle();
        bundle.putString("publishOrderId", publishOrderId + "");
        bundle.putString("mid", mid);
        bundle.putString("unit", unit);
        intent(SubmitOrderActivity.class, bundle);
        finish();
    }

    @OnClick(R.id.iv_head)
    public void toPersonInfo() {
        Bundle bundle = new Bundle();
        bundle.putString("mid", mid);
        intent(PersonInfoActivityTwo.class, bundle);
    }

    @OnClick(R.id.ll_collect)
    public void collect() {
        collectPresenter.reqeust("Bearer " + token, publishOrderId + "", "1");
    }

    @OnClick(R.id.ll_collected)
    public void cancelCollect() {
        collectPresenter.reqeust("Bearer " + token, publishOrderId + "", "0");
    }

    @OnClick(R.id.iv_jubao)
    public void jubao() {
        showDialog();
    }

    class OrderCall implements DataCall<Order> {

        @Override
        public void success(Order data, Object... args) {
            if (data.getRecords() == null || data.getRecords().size() < 2) {
                rv_like.setVisibility(View.GONE);
                tv_like.setVisibility(View.GONE);
            } else {
                rv_like.setVisibility(View.VISIBLE);
                tv_like.setVisibility(View.VISIBLE);
            }
            //添加列表并刷新
            if (homeOrderPresenter.getPage() == 1) {
                orders.clear();
            }
            orderLikeListAdapter.setNewInstance(data.getRecords());
            orderLikeListAdapter.notifyDataSetChanged();
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    private void showDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_report, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        LinearLayout ll_copy = dialogView.findViewById(R.id.ll_copy);
        LinearLayout ll_jubao = dialogView.findViewById(R.id.ll_jubao);
        LinearLayout ll_lahei = dialogView.findViewById(R.id.ll_lahei);
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        ll_copy.setVisibility(View.GONE);
        ll_lahei.setVisibility(View.GONE);
        ll_jubao.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("mid", mid);
            intent(ReportActivity.class, bundle);
            bottomDialog.dismiss();
        });

    }

    class OrderDetailCall implements DataCall<OrderDetail> {

        @Override
        public void success(OrderDetail data, Object... args) {
            setOrderDetail(data);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            if (e.getCode().equals("8000")) {
                UIUtils.showToastSafe("登录过期，请重新登录");
                intent(LoginActivity.class);
                finish();
            }
        }
    }

    class OrderCommentCall implements DataCall<OrderComment> {

        @Override
        public void success(OrderComment data, Object... args) {
            int total = data.getTotal();
            if (total > 0) {
                rl_pl.setVisibility(View.VISIBLE);
                tv_pj_num.setText("（" + total + "）");
                tv_hp.setText(data.getNiceScale() + "%");
            } else {
                rl_pl.setVisibility(View.GONE);
            }
            if (orderCommentPresenter.getPage() == 1) {
                commentList.clear();
            }
            orderCommentAdapter.setNewInstance(data.getList());
            orderCommentAdapter.notifyDataSetChanged();
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class CollectCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            isShow = !isShow;
            if (isShow) {
                ll_collect.setVisibility(View.GONE);
                ll_collected.setVisibility(View.VISIBLE);
            } else {
                ll_collect.setVisibility(View.VISIBLE);
                ll_collected.setVisibility(View.GONE);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    private void setOrderDetail(OrderDetail data) {
        categoryId = data.getCategoryId();
        mid = data.getMid();
        tv_name.setText(data.getNickName());
        tv_category.setText(data.getCategory());
        tv_other.setText(data.getArea() + "地区," + data.getCategory());
        tv_address.setText(data.getArea());
        List<OrderDetail.TimeDTO> times = data.getTime();
        String time = "";
        if (times.size() > 0) {
            for (int i = 0; i < times.size(); i++) {
                time = time + times.get(i).getTips();
            }
        }
        tv_week.setText(time);
        tv_tips.setText(data.getGender());
        tv_content.setText(data.getOtherDesc());
        if (data.getPrice().contains(".")) {
            String[] split = data.getPrice().split("\\.");
            tv_price.setText(split[0]);
        } else {
            tv_price.setText(data.getPrice());
        }
        if (data.getMid().equals(userId + "")) {
            bt_submit.setVisibility(View.GONE);
        } else {
            bt_submit.setVisibility(View.VISIBLE);
        }
        unit = data.getUnit();
        isShow = data.isCollect();
        if (data.isCollectButton()) {
            if (data.isCollect()) {
                ll_collect.setVisibility(View.GONE);
                ll_collected.setVisibility(View.VISIBLE);
            } else {
                ll_collect.setVisibility(View.VISIBLE);
                ll_collected.setVisibility(View.GONE);
            }
        } else {
            ll_collect.setVisibility(View.GONE);
            ll_collected.setVisibility(View.GONE);
        }
        Glide.with(OrderDetailActivity.this).load(data.getImageUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        List<String> imgs = data.getImgs();
        if (imgs.size() > 0) {
            ll_imgs.setVisibility(View.VISIBLE);
            if (imgs.get(0) != null && !TextUtils.isEmpty(imgs.get(0))) {
//                Glide.with(OrderDetailActivity.this).load(imgs.get(0)).into(iv_img_one);
                GlideUtils.loadImgTwo(OrderDetailActivity.this, imgs.get(0), 30, iv_img_one);
            }
            if (imgs.size() > 1) {
                if (imgs.get(1) != null && !TextUtils.isEmpty(imgs.get(1))) {
//                    Glide.with(OrderDetailActivity.this).load(imgs.get(1)).into(iv_img_two);
                    GlideUtils.loadImgTwo(OrderDetailActivity.this, imgs.get(1), 30, iv_img_two);
                }
            }
            if (imgs.size() > 2) {
                if (imgs.get(2) != null && !TextUtils.isEmpty(imgs.get(2))) {
//                    Glide.with(OrderDetailActivity.this).load(imgs.get(2)).into(iv_img_three);
                    GlideUtils.loadImgTwo(OrderDetailActivity.this, imgs.get(2), 30, iv_img_three);
                }
            }
        } else {
            ll_imgs.setVisibility(View.GONE);
        }
        homeOrderPresenter.reqeust(true, categoryId, "", age, auto, cityCode, cityName, gender, price);
        orderCommentPresenter.reqeust(true, "Bearer " + token, data.getPublishOrderId());
        int visitCount = data.getVisitCount();
        if (visitCount > 0) {
            tv_liulan.setVisibility(View.VISIBLE);
            tv_liulan.setText(visitCount + " 浏览");
        } else {
            tv_liulan.setVisibility(View.GONE);
        }

        if ("-1".equals(data.getUnit())){
            tv_unit.setText("/一口价");
        }else if ("0".equals(data.getUnit())){
            tv_unit.setText("/小时");
        }else if ("1".equals(data.getUnit())){
            tv_unit.setText("/天");
        }
    }

    @Override
    protected void destoryData() {

    }
}
